package com.fjh.springboot_01.controller;

import com.fjh.springboot_01.pojo.Result;
import com.fjh.springboot_01.pojo.payment.PaymentOrder;
import com.fjh.springboot_01.service.PaymentService;
import com.fjh.springboot_01.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.HashMap;
import jakarta.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/payment")
public class PaymentController {

    @Autowired
    private PaymentService paymentService;

    /**
     * 创建支付订单
     * @param bookingId 预约ID
     * @return 支付订单信息
     */
    @PostMapping("/create")
    public Result<PaymentOrder> createPayment(@RequestParam Integer bookingId) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        Integer role = (Integer) map.get("role");
        
        // 只有学生可以创建支付
        if (role != 0) {
            return Result.error("只有学生可以支付");
        }
        
        try {
            PaymentOrder order = paymentService.createPaymentOrder(bookingId);
            return Result.success(order);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 通过课程安排ID创建支付订单
     * @param scheduleId 课程安排ID
     * @return 支付订单信息
     */
    @PostMapping("/create/schedule")
    public Result<PaymentOrder> createPaymentBySchedule(@RequestParam Integer scheduleId) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        Integer role = (Integer) map.get("role");
        
        // 只有学生可以创建支付
        if (role != 0) {
            return Result.error("只有学生可以支付");
        }
        
        try {
            PaymentOrder order = paymentService.createPaymentOrderByScheduleId(scheduleId);
            return Result.success(order);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取支付宝支付表单
     * @param orderNo 订单编号
     * @return 支付表单HTML
     */
    @GetMapping("/alipay")
    public Result<String> alipay(@RequestParam String orderNo) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        Integer role = (Integer) map.get("role");
        
        // 只有学生可以支付
        if (role != 0) {
            return Result.error("只有学生可以支付");
        }
        
        try {
            String form = paymentService.createAlipayForm(orderNo);
            return Result.success(form);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 支付宝异步通知接口
     * 注意：这里不需要@RequestParam，支付宝会将参数以表单形式发送
     * @return 处理结果
     */
    @PostMapping("/alipay/notify")
    public String alipayNotify(HttpServletRequest request) {
        // 获取支付宝POST过来的反馈信息
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        
        for (String name : requestParams.keySet()) {
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }
        
        System.out.println("收到支付宝异步通知: " + params);
        
        boolean result = paymentService.handleAlipayNotify(params);
        return result ? "success" : "failure";
    }

    /**
     * 查询支付订单状态
     * @param orderNo 订单编号
     * @return 订单信息
     */
    @GetMapping("/status")
    public Result<PaymentOrder> getPaymentStatus(@RequestParam String orderNo) {
        System.out.println("查询订单状态, 订单号: " + orderNo);
        
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        
        PaymentOrder order = paymentService.getPaymentOrderByOrderNo(orderNo);
        if (order == null) {
            System.out.println("订单不存在, 订单号: " + orderNo);
            return Result.error("订单不存在");
        }
        
        System.out.println("查询到订单: ID=" + order.getId() + ", 状态=" + order.getStatus() + 
                ", 支付宝交易号=" + order.getTradeNo() + ", 支付时间=" + order.getPaymentTime());
        
        // 验证订单所属者
        Integer role = (Integer) map.get("role");
        if ((role == 0 && !order.getStudentId().equals(userId)) || 
            (role == 1 && !order.getTeacherId().equals(userId))) {
            System.out.println("用户无权查看该订单, 用户ID=" + userId + ", 角色=" + role + 
                    ", 学生ID=" + order.getStudentId() + ", 教师ID=" + order.getTeacherId());
            return Result.error("无权查看该订单");
        }
        
        System.out.println("返回订单状态, 订单号=" + orderNo + ", 状态=" + order.getStatus());
        return Result.success(order);
    }

    /**
     * 获取学生的支付订单列表
     * @return 支付订单列表
     */
    @GetMapping("/student/list")
    public Result<List<PaymentOrder>> getStudentPayments() {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        Integer role = (Integer) map.get("role");
        
        if (role != 0) {
            return Result.error("只有学生可以查看");
        }
        
        List<PaymentOrder> orders = paymentService.getStudentPaymentOrders(userId);
        return Result.success(orders);
    }

    /**
     * 获取教师的收款订单列表
     * @return 支付订单列表
     */
    @GetMapping("/teacher/list")
    public Result<List<PaymentOrder>> getTeacherPayments() {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        Integer role = (Integer) map.get("role");
        
        if (role != 1) {
            return Result.error("只有教师可以查看");
        }
        
        List<PaymentOrder> orders = paymentService.getTeacherPaymentOrders(userId);
        return Result.success(orders);
    }

    /**
     * 手动更新订单状态（临时解决方案）
     * 由于支付宝异步通知在本地开发环境难以接收，添加此接口用于前端手动触发更新订单状态
     * @param orderNo 订单编号
     * @param tradeNo 支付宝交易号
     * @return 更新结果
     */
    @PostMapping("/manual-update")
    public Result<Void> manualUpdatePaymentStatus(@RequestParam String orderNo, @RequestParam(required = false) String tradeNo) {
        System.out.println("手动更新订单状态: 订单号=" + orderNo + ", 支付宝交易号=" + tradeNo);
        
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        Integer role = (Integer) map.get("role");
        
        System.out.println("用户ID=" + userId + ", 角色=" + role);
        
        // 获取订单信息
        PaymentOrder order = paymentService.getPaymentOrderByOrderNo(orderNo);
        if (order == null) {
            System.out.println("订单不存在: " + orderNo);
            return Result.error("订单不存在");
        }
        
        System.out.println("订单信息: ID=" + order.getId() + ", 学生ID=" + order.getStudentId() 
                + ", 教师ID=" + order.getTeacherId() + ", 状态=" + order.getStatus());
        
        // 验证订单是否属于当前用户（学生或教师）
        boolean hasPermission = (role == 0 && order.getStudentId().equals(userId)) // 学生可以更新自己的订单
                || (role == 1 && order.getTeacherId().equals(userId)) // 教师可以更新有自己作为教师的订单
                || (role == 2); // 管理员可以更新任何订单
        
        if (!hasPermission) {
            System.out.println("用户无权更新该订单状态: 用户ID=" + userId + ", 角色=" + role);
            return Result.error("无权更新该订单状态");
        }
        
        // 如果订单已经是支付成功状态，直接返回成功
        if (order.getStatus() == 1) {
            System.out.println("订单已经是支付成功状态: " + orderNo);
            return Result.success();
        }
        
        try {
            // 使用默认的交易号（如果未提供）
            String actualTradeNo = tradeNo != null ? tradeNo : "manual_" + System.currentTimeMillis();
            
            // 更新订单状态
            int rows = paymentService.manualUpdatePaymentStatus(orderNo, actualTradeNo);
            
            if (rows > 0) {
                System.out.println("订单状态更新成功: " + orderNo);
                return Result.success();
            } else {
                System.out.println("订单状态更新失败: " + orderNo);
                return Result.error("更新订单状态失败");
            }
        } catch (Exception e) {
            System.out.println("更新订单状态异常: " + e.getMessage());
            return Result.error("更新订单状态异常: " + e.getMessage());
        }
    }
} 